package com.pj.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pj.conf.RagflowConfig;
import com.pj.service.RagFlowChatAssistantService;
import com.pj.service.RagFlowChatService;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zzy
 * @date 2025/6/21 16:35
 * @description : 与聊天助手中的会话 管理
 */
@Service
public class RagFlowChatServiceImpl implements RagFlowChatService {

    private final WebClient webClient;
    private final RagflowConfig ragflowConfig;

    public RagFlowChatServiceImpl(WebClient.Builder webClient, RagflowConfig ragflowConfig) {
        this.webClient = webClient.baseUrl(ragflowConfig.getBaseUrl()).build();
        this.ragflowConfig = ragflowConfig;
    }


    /**
     * 添加会话
     * @param RagFlowApi
     * @param requestBody
     * @return
     */
    @Override
    public List<Map<String, Object>> addChat(String RagFlowApi, Map<String, Object> requestBody) {
        // 请求并直接转换成 Map
        Map<String, Object> response = webClient.post()
                .uri(RagFlowApi)
                .header("Authorization", "Bearer " + ragflowConfig.getApiKey())
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {})
                .block();

        List<Map<String, Object>> resultList = new ArrayList<>();

        if (response != null && Integer.valueOf(response.get("code").toString()) == 0) {
            // 成功，提取 data
            Object data = response.get("data");
            ObjectMapper objectMapper = new ObjectMapper();

            if (data instanceof List) {
                // data 是数组
                resultList = objectMapper.convertValue(
                        data, new TypeReference<List<Map<String, Object>>>() {}
                );
            } else if (data instanceof Map) {
                // data 是单个对象
                Map<String, Object> singleData = objectMapper.convertValue(
                        data, new TypeReference<Map<String, Object>>() {}
                );
                resultList.add(singleData);
            }

            if (!resultList.isEmpty()) {
                System.out.println("创建成功：" + resultList.get(0).get("name"));
            }
        } else if (response != null) {
            // 失败，直接输出 message
            System.out.println("创建失败，错误信息：" + response.get("message"));
        } else {
            System.out.println("接口响应为空！");
        }

        return resultList;
    }

    @Override
    public List<Map<String, Object>> listChat(String RagFlowApi) {
        Map<String, Object> response = webClient.get()
                .uri(RagFlowApi)
                .header("Authorization", "Bearer " + ragflowConfig.getApiKey())
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {})
                .block();

        List<Map<String, Object>> resultList = new ArrayList<>();

        if (response != null && Integer.valueOf(response.get("code").toString()) == 0) {
            Object data = response.get("data");
            if (data != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                resultList = objectMapper.convertValue(data, new TypeReference<List<Map<String, Object>>>() {});
            }
        } else if (response != null) {
            System.out.println("查询失败，错误信息：" + response.get("message"));
        } else {
            System.out.println("接口响应为空！");
        }

        return resultList;
    }


    @Override
    public Map<String, Object> chat(String RagFlowApi, Map<String, Object> requestBody) {

        Map<String, Object> response = webClient.post()
                .uri(RagFlowApi)
                .header("Authorization", "Bearer " + ragflowConfig.getApiKey())
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {})
                .block();

        if (response != null && Integer.valueOf(response.get("code").toString()) == 0) {
            // 成功，提取 data
            Object data = response.get("data");
            if (data instanceof Map) {
                Map<String, Object> dataMap = (Map<String, Object>) data;
                System.out.println("回答内容：" + dataMap.get("answer"));
            } else if (data instanceof Boolean) {
                System.out.println("操作成功，返回结果为 true");
            } else {
                System.out.println("返回结果：" + data);
            }
        } else if (response != null) {
            // 失败，直接输出 message
            System.out.println("创建失败，错误信息：" + response.get("message"));
        } else {
            System.out.println("接口响应为空！");
        }

        return response;
    }



    @Override
    public void chatStream(String ragFlowApi, String question, String sessionId, ResponseBodyEmitter emitter) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("question", question); // 必填
        requestBody.put("stream", true);
        requestBody.put("session_id", sessionId);

        System.out.println("url:"+ragflowConfig.getBaseUrl() + ragFlowApi);
        WebClient.create()
                .post()
                .uri( ragflowConfig.getBaseUrl() + ragFlowApi)
                .header("Authorization", "Bearer " + ragflowConfig.getApiKey())
                .bodyValue(requestBody)
                .retrieve()
                .bodyToFlux(String.class) // 流式返回每一块 JSON 字符串
                .doOnNext(data -> {
                    try {
                        System.out.println("流式数据：" + data);
                        // 解析 JSON
                        JSONObject jsonObject = JSON.parseObject(data);
                        Integer code = jsonObject.getInteger("code");
                        Object dataObj = jsonObject.get("data");

                        if (dataObj instanceof Map) {
                            Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                            String answer = dataMap.get("answer").toString();
                            emitter.send("data: " + answer + "\n\n");
                        }
                        // 如果收到 {"code":0, "data": true}，表示流结束
                        else if (dataObj instanceof Boolean && (Boolean) dataObj) {
                            emitter.complete();
                        }

                        // 正常数据
                        if (code != null && code == 0 && dataObj instanceof JSONObject) {
                            String answer = ((JSONObject) dataObj).getString("answer");
                            emitter.send("data: " + answer + "\n\n");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                })

                .doOnError(error -> {
                    try {
                        emitter.send("data: 发生错误: " + error.getMessage() + "\n\n");
                        emitter.completeWithError(error);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                })
                .doOnComplete(() -> {
                    try {
                        emitter.complete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                })
                .subscribe();
    }



}
